package com.lanyun.controller;/**
 * @author zhy
 * @date 2021/1/6 - 9:29
 */

import ch.qos.logback.core.net.SyslogOutputStream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lanyun.pojo.Admin;
import com.lanyun.pojo.Function;
import com.lanyun.pojo.Privilege;
import com.lanyun.pojo.Role;
import com.lanyun.service.AdminService;
import com.lanyun.service.FunctionService;
import com.lanyun.service.PrivilegeService;
import com.lanyun.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**

 @ClassName AdminController
 @Description xxx
 @Author zhy
 @Date 2021/1/6 - 9:29
 @Version 1.0
 **/
@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private PrivilegeService privilegeService;

    @Autowired
    private FunctionService functionService;

    @RequestMapping("/login")
    public String login(Model model , @Validated Admin admin , BindingResult result , HttpSession session) throws JsonProcessingException {
        System.out.println(admin.getLoginName()+"  "+admin.getPwd());
        List errorList;//--------错误信息集合
        HashMap<String, String> map = new HashMap();
        if (result.hasErrors()){
            errorList = result.getAllErrors();
            for (int i = 0; i < errorList.size(); i++) {
                FieldError error = (FieldError) errorList.get(i);
                String field = error.getField();
                String message = error.getDefaultMessage();
                System.out.println(field+"出错  "+"错误信息:"+message);
                map.put(field,message);
                model.addAllAttributes(map);
            }
            System.out.println(map.size());
            System.out.println(map.keySet());
            return "login";
        }else{
            if (adminService.findByName(admin)==null){
                model.addAttribute("error","登录名或密码错误，请重新输入！！！");
                return "login";
            }else if (adminService.findByName(admin)!=null&&adminService.findByName(admin).getState()==1){
                model.addAttribute("state","该管理员已被禁用，请联系老大操作一下！！！");
                return "login";
            }
            // 将登录成功的角色存入
            session.setAttribute("admin",adminService.findByName(admin));
            model.addAttribute("admin",adminService.findByName(admin));
            session.setAttribute("loginer",adminService.findByName(admin));
            return "index";
        }
    }

    List<Integer> list;//------权限id集合
    List<Privilege> privilegeList;//-----权限对象集合
    List<Function> functionList;//----功能集合
    @RequestMapping("/getMenu")
    @ResponseBody
    public Object getMenu(Integer rid) throws JsonProcessingException {
        System.out.println("角色id： "+rid);
        list = roleService.getPrivilege(rid);//----根据角色id通过中间表查询出所有的权限id集合。
        privilegeList = privilegeService.findPriviById(list);//----根据拿到的权限id集合拿到该角色的所有权限对象
        List<Map> result = new ArrayList<>();//----返回Json的最外层list
        for (int i = 0; i <privilegeList.size() ; i++) {//遍历该角色下的所有权限对象
            Map privilegeMap = new HashMap();//创建第一层map，存放权限名及该权限下的功能
            privilegeMap.put("Text",privilegeList.get(i).getName());//--存放权限名
            List<Map> children = new ArrayList<>();//----存放功能list
            functionList = functionService.findFunction(privilegeList.get(i).getPid());//循环传入权限id,拿到该权限下的所有功能集合
            for (int j = 0; j <functionList.size() ; j++) {//遍历不同权限下的所有功能
                Map functionMap = new HashMap();//--第二层map集合，存放该权限下的功能名及urlmap
                functionMap.put("Text",functionList.get(j).getName());//存放功能名
                Map urlMap = new HashMap();//第三层map，存放url路径
                urlMap.put("url",functionList.get(j).getUrl());//存放url路径
                functionMap.put("attributes",urlMap);//把urlmap添加到功能map中
                children.add(functionMap);//功能集合添加功能map
            }
            privilegeMap.put("children",children);//权限map添加不同权限下的功能集合
            result.add(privilegeMap);//将存放好的功能集合放入最外层list中
        }
        //------------------封装完毕，将封装好的result集合转为Json-----------------------
        ObjectMapper mapper = new ObjectMapper();
        String Json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        System.out.println("封装的Json为： "+Json);
        return result;
    }

    @RequestMapping("/")
    public String defaultPage(){
        return "login";
    }

    @RequestMapping("/showAll")
    public String showAll(Model model){//查找所有管理员
        List<Admin> adminList = adminService.findAdmin();
        model.addAttribute("alladmin",adminList);
        model.addAttribute("count",adminList.size());
        return "adminpage";
    }
    @RequestMapping("/showAll1")
    @ResponseBody
    public Object showAll1(){
        List<Admin> adminList = adminService.findAdmin();
        return adminList;
    }


    @RequestMapping("/changeRole")
    @ResponseBody
    public Object changeRole(Integer id){
        List<Admin> admins = adminService.findAdminById(id);
        return admins;
    }

    @RequestMapping("/addAdmin")
    public String addAdmin(Admin admin){//添加管理员
        System.out.println("要增加的管理员属性：  "+admin);
        Integer result = adminService.insertAdmin(admin);
        if (result==1){return "redirect:/showAll";}
        return "";
    }

    @RequestMapping("/del")
    @ResponseBody
    public Object del(Integer id){//单项删除管理员，点击删除按钮，拿到对应的id进行删除
        System.out.println("单项删除管理员拿到的id：  "+id);
        Integer result = adminService.deleteAdmin(id);
        if (result==1){
            return result;
        }
        return "";
    }

    @RequestMapping("/delSome")
    @ResponseBody
    public Object delSome(String ids){//批量删除--拿到选中的CheckBox--id进行批量删除
        System.out.println("批量删除拿到的id： ---  "+ids);
        Integer result = adminService.deleteSomeAdmin(ids);
        System.out.println("---------"+result);
        if (result>=1){
            return result;
        }else {
            return "";
        }
    }

    @RequestMapping("/updateAdmin")
    @ResponseBody
    public Object updateAdmin(Integer id){//查找当前管理员的所有信息，数据回显，修改功能
        System.out.println("修改管理员拿到的id:  -- "+id);
        Admin admin = adminService.findAdmin_update(id);
        return admin;
    }

    @RequestMapping("/updateAdminReal")
    public String updateAdminReal(Admin admin){//拿到修改后的管理员信息，进行修改操作
        System.out.println("修改后的管理员信息：  --  "+admin);
        Integer result = adminService.updateAdmin(admin);
        if (result==1){
            return "redirect:/showAll";
        }
        return "";
    }

    @RequestMapping("/adminStop")
    @ResponseBody
    public Object adminStop(Integer id){//管理员停用，拿到管理员id，修改管理员状态
        System.out.println("用户停用拿到的管理员id为：  -- "+id);
        Integer result = adminService.stateStop(id);
        if (result==1){
            return result;
        }
        return "";
    }

    @RequestMapping("/adminStart")
    @ResponseBody
    public Object adminStart(Integer id){//管理员停用，拿到管理员id，修改管理员状态
        System.out.println("用户启用拿到的管理员id为：  -- "+id);
        Integer result = adminService.stateStart(id);
        if (result==1){
            return result;
        }
        return "";
    }

    @RequestMapping("/deleteSession")//退出登录，使session失效
    public String deleteSession(HttpServletRequest request){
        System.out.println(request.getSession().getAttribute("loginer"));
       request.getSession().invalidate();
        System.out.println("失效后的session："+request.getSession().getAttribute("loginer"));
       return "login";
    }
}
